import { setStore, getStore } from '@/util/store'
import {validatenull} from '@/util/validate'
import { deepClone } from '@/util/util'
import { loginByUsername, logout, getButtons } from '@/api/system/user'
import { formatPath } from '@/router/avue-router'
import {getRoutes, getTopMenu} from '@/api/system/menu'

const user = {
  state: {
    userInfo: getStore({name: 'userInfo'}) || {},
    permission: getStore({name: 'permission'}) || {},
    roles: [],
    menuId: {},
    menu: getStore({ name: 'menu' }) || [],
    menuAll: getStore({ name: 'menuAll' }) || [],
    token: getStore({ name: 'token' }) || '',
    refreshToken: getStore({ name: 'refreshToken' }) || ''
  },
  actions: {
    //根据用户名登录
    async LoginByUsername ({ commit }, userInfo = {}) {
      const { data } = await loginByUsername(userInfo.username, userInfo.password, userInfo.code)
      commit('SET_TOKEN', data.token);
      commit('SET_REFRESH_TOKEN', data.refreshToken)
      commit('SET_USERIFNO', data);
      commit('DEL_ALL_TAG');
      commit('CLEAR_LOCK');
      return Promise.resolve(data)
    },
    //根据手机号登录
    // LoginByPhone ({ commit }, userInfo) {
    //   return new Promise((resolve) => {
    //     loginByUsername(userInfo.phone, userInfo.code).then(({ data }) => {
    //       const data = res.data.data;
    //       commit('SET_TOKEN', data);
    //       commit('DEL_ALL_TAG');
    //       commit('CLEAR_LOCK');
    //       resolve();
    //     })
    //   })
    // },
    // 登出
    async LogOut ({ state, commit }) {
      await logout(state.refreshToken)
      commit('SET_TOKEN', '')
      commit('SET_REFRESH_TOKEN', '')
      commit('SET_MENUALL_NULL', []);
      commit('SET_MENU', [])
      commit('SET_ROLES', [])
      commit('DEL_ALL_TAG', []);
      commit('CLEAR_LOCK');
      return Promise.resolve()
    },
    //注销session
    async FedLogOut ({ commit }) {
      commit('SET_TOKEN', '')
      commit('SET_REFRESH_TOKEN', '')
      commit('SET_MENUALL_NULL', []);
      commit('SET_MENU', [])
      commit('SET_ROLES', [])
      commit('DEL_ALL_TAG', []);
      commit('CLEAR_LOCK');
      return Promise.resolve()
    },
    // 顶部菜单（暂时没用）
    async GetTopMenu () {
      const { data } = await getTopMenu()
      return Promise.resolve(data ?? [])
    },
    //获取系统菜单
    async GetMenu ({ commit, dispatch }, topMenuId) {
      const { data } = await getRoutes(topMenuId)
      let menu = deepClone(data);
      menu.forEach(ele => formatPath(ele, true));
      commit('SET_MENUALL', menu)
      commit('SET_MENU', menu)
      dispatch('GetButtons');
      return Promise.resolve(menu)
    },
    //获取系统按钮
    async GetButtons({commit}) {
      const { data } = await getButtons()
      commit('SET_PERMISSION', data);
      return Promise.resolve(data)
    },
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
      setStore({ name: 'token', content: state.token })
    },
    SET_REFRESH_TOKEN: (state, refreshToken) => {
      state.refreshToken = refreshToken;
      setStore({ name: 'refreshToken', content: state.refreshToken })
    },
    SET_MENUID (state, menuId) {
      state.menuId = menuId;
    },
    SET_USERIFNO: (state, userInfo) => {
      if (validatenull(userInfo.avatar)) {
        userInfo.avatar = "/img/bg/img-logo.png";
      }
      state.userInfo = userInfo;
      setStore({name: 'userInfo', content: state.userInfo})
    },
    SET_MENUALL: (state, menuAll) => {
      let menu = state.menuAll;
      menuAll.forEach(ele => {
        if (!menu.find(item => item.path === ele.path)) {
          menu.push(ele);
        }
      })
      state.menuAll = menu
      setStore({ name: 'menuAll', content: state.menuAll })
    },
    SET_MENUALL_NULL: (state) => {
      state.menuAll = []
      setStore({ name: 'menuAll', content: state.menuAll })
    },
    SET_MENU: (state, menu) => {
      state.menu = menu
      setStore({ name: 'menu', content: state.menu })
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_PERMISSION: (state, permission) => {
      state.permission = {};
      permission.forEach(ele => {
        state.permission[ele] = true;
      });
      setStore({name: 'permission', content: state.permission})
    }
  }

}
export default user